<template>
  <div>
    <!-- 弹出框 -->
    <el-dialog
      :title="dialogType"
      :visible.sync="dialogVisable"
      width="810px"
      top="50vh"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      custom-class="samples-dialog"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <!-- esc按钮和点击遮罩不会关闭弹窗，需要设置配置项 -->
      <el-row>
        <el-col :span="24">
          <el-form
            ref="tableForm"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            class="samples-dialog-form"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="模板名称：" prop="name">
                  <el-input
                    v-model="formData.name"
                    placeholder="请输入"
                    class="samples-must-declared"
                    size="small"
                    style="width:100%"
                    clearable
                  />
                  <template slot="error" slot-scope="scope">
                    <div class="sample-error-message">{{ scope.error }}</div>
                  </template>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="适用分类：" prop="classifyName">
                  <el-select
                    v-model="formData.classifyName"
                    clearable
                    size="small"
                    style="width: 100%"
                    placeholder="请选择"
                    @change="classifyNameChange()"
                  >
                    <el-option
                      v-for="item in contractClassify"
                      :key="item.code"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                  <template slot="error" slot-scope="scope">
                    <div class="sample-error-message">{{ scope.error }}</div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="适用类型：" prop="typeArr">
                  <el-checkbox-group
                    v-for="(item,i) in ContractType"
                    :key="i"
                    v-model="formData.typeArr"
                    style="width:100px;float:left;"
                    @change="changeTypeArr"
                  >
                    <el-checkbox :label="item.name" />
                  </el-checkbox-group>
                  <template slot="error" slot-scope="scope">
                    <div class="sample-error-message">{{ scope.error }}</div>
                  </template>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                  <el-form-item label="附件类型：" prop="a7" class="samples-mb-75 add-star" style="max-height:200px;">
                    <el-row
                      v-for="(item, index) in formData.contractAttachmentTypeItemList"
                      :key="index"
                      class="samples-mb-15 endInput"
                    >
                      <el-col :span="12">
                        <el-form-item :rules="formRules.contractAttachmentTypeItemList" label-width="0" :prop="`contractAttachmentTypeItemList[${index}].name`" class="samples-mb-75">
                          <el-input
                            v-model="item.name"
                            style="width:280px"
                            placeholder="附件类型"
                            size="small"
                          />
                          <template slot="error" slot-scope="scope">
                            <div class="sample-error-message">{{ scope.error }}</div>
                          </template>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-col v-show="delSpecialBtn" :span="12" class="spec-op">
                          <el-button
                            type="text"
                            class="samples-text-button-disabled"
                            @click="delSpecial(index)"
                          >删 除</el-button>
                        </el-col>
                      </el-col>
                    </el-row>
                  </el-form-item>
              </el-col>
            </el-row>
          
            <el-row>
              <el-col :span="12">
                <el-form-item>
                  <el-button class="add-btn" type="primary" size="small" plain @click="addSpecial">
                    <i class="el-icon-plus">添 加</i>
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <el-row class="samples-dialog-footer">
        <el-row class="samples-float-right">
          <!-- handleClose关闭弹窗事件，点击直接关闭，不会弹出确认框 -->
          <el-button size="small" type="primary" plain @click="handleClose">取 消</el-button>
          <el-button size="small" type="primary" @click="submitForm()">确 认</el-button>
        </el-row>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import * as contractCorrelationApi from '@/api/contractManage/contractCorrelation'
export default {
  props: {
    dialogType: {
      type: String,
      required: true
    },
    listData: {
      type: Object,
      default: () => {}
    },
    dialogShow: {
      type: Boolean,
      default: false
    },
    contractClassify: {
      type: Array,
      default: () => []
    },
    singleContractType: {
      type: Array,
      default: () => []
    },
    projectContractType: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisable: this.dialogShow,
      // 多选框的默认空数组
      ContractType: [],
      // 双列表单
      formData: {
        id: '',
        name: '',
        classifyName: '',
        classifyId: '',
        typeArr: [],
        typeId: '',
        typeName: '',
        contractAttachmentTypeItemList: [{ name: '' }]
      },
      // 删除按钮的show
      delSpecialBtn: false,
      formRules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        typeArr: [{ required: true, message: '请选择', trigger: 'blur' }],
        classifyName: [{ required: true, message: '请选择', trigger: 'blur' }],
        contractAttachmentTypeItemList: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  watch: {
    dialogShow: {
      handler: function(val, oldval) {
        console.log('父组件传过来的值', val)
        if (val === true) {
          this.dialogVisable = this.dialogShow
          this.getListData()
        }
      }
    }
  },
  methods: {
    // 适用分类发生改变发生改变
    classifyNameChange() {
      this.formData.typeArr = []
      this.formData.typeId = ''
      this.formData.typeName = ''
      if (this.formData.classifyName == '单项合同') {
        this.ContractType = this.singleContractType
      } else {
        this.ContractType = this.projectContractType
      }
      for (let i = 0; i < this.contractClassify.length; i++) {
        if (this.formData.classifyName == this.contractClassify[i].name) {
          this.formData.classifyId = this.contractClassify[i].code
        }
      }
    },
    // 给表单的产品特点添加一个特点
    addSpecial() {
      this.formData.contractAttachmentTypeItemList.push({ name: '' })
      if (this.formData.contractAttachmentTypeItemList.length > 1) {
        this.delSpecialBtn = true
      }
    },
    // 我们的产品少了一个特点
    delSpecial(val) {
      this.formData.contractAttachmentTypeItemList.splice(val, 1)
      if (this.formData.contractAttachmentTypeItemList.length == 1) {
        this.delSpecialBtn = false
      }
    },
    //   关闭表单
    handleClose() {
      this.dialogVisable = false
      this.$emit('dialogDisplay', this.dialogVisable)
      // tableForm
      this.ContractType = []
      this.$refs['tableForm'].resetFields()
    },
    // 改变适用类型
    changeTypeArr() {
      const typeIdArr = []
      if (this.formData.classifyName == '单项合同') {
        // this.ContractType = this.singleContractType
        for (let i = 0; i < this.formData.typeArr.length; i++) {
          for (let j = 0; j < this.singleContractType.length; j++) {
            if (this.singleContractType[j].name == this.formData.typeArr[i]) {
              // this.formData.typeId.concat(this.singleContractType[j].code) + ','
              // this.formData.typeId += this.singleContractType[j].code
              // this.formData.typeId += ','
              typeIdArr.push(this.singleContractType[j].code)
            }
          }
        }
      } else {
        for (let i = 0; i < this.formData.typeArr.length; i++) {
          for (let j = 0; j < this.projectContractType.length; j++) {
            if (this.projectContractType[j].name == this.formData.typeArr[i]) {
              // this.formData.typeId.concat(this.singleContractType[j].code) + ','
              // this.formData.typeId += this.projectContractType[j].code
              // this.formData.typeId += ','
              typeIdArr.push(this.singleContractType[j].code)
            }
          }
        }
      }
      typeIdArr.sort()
      // this.formData.typeArr.sort()
      // const arr = []
      // for (let i = 0; i < this.ContractType.length; i++) {
      //   for (let j = 0; j < typeIdArr.length; j++) {
      //     if (typeIdArr[j] == this.ContractType[i].code) {
      //       arr.push(this.ContractType[i].name)
      //     }
      //   }
      // }
      this.formData.typeId = typeIdArr.join(',')
    },
    getData() {
      if (this.dialogType === '新增附件') {
        this.$parent.getList()
      } else {
        this.$parent.getData()
      }
    },
    // 提交表单
    submitForm() {
      console.log(this.formData.typeArr)
      console.log(this.ContractType)
      this.$refs['tableForm'].validate((valid) => {
        if (valid) {
          // const arr = []
          // for (let i = 0; i < this.ContractType.length; i++) {
          //   for (let j = 0; j < this.formData.typeArr.length; j++) {
          //     if (this.ContractType[i].name == this.formData.typeArr[i]) {
          //       arr.push(this.formData.typeArr[i])
          //     }
          //   }
          // }
          // this.formData.typeArr = arr
          if (this.dialogType === '新增附件') {
            // let typeIdArr = [],

            this.formData.typeName = this.formData.typeArr.join(',')
            console.log(this.formData)
            contractCorrelationApi
              .contractAttachmentTypeCreate(this.formData)
              .then(res => {
                console.log(res.data)
                if (res.code == 1) {
                  //  this.$parent.fatherMethod();
                  this.getData()
                  this.handleClose()
                  this.$notify({
                    title: '成功',
                    message: '新增成功',
                    type: 'success',
                    duration: '3000'
                  })
                } else {
                  this.$notify.error({
                    title: '错误',
                    message: res.msg,
                    duration: '3000'
                  })
                }
              })
          } else if (this.dialogType === '编辑附件') {
            this.formData.id = this.listData.id
            this.formData.typeName = this.formData.typeArr.join(',')
            contractCorrelationApi
              .contractAttachmentTypeEdit(this.formData)
              .then(res => {
                console.log(res.data)
                if (res.code == 1) {
                  this.getData()
                  this.handleClose()
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: '3000'
                  })
                } else {
                  this.$notify.error({
                    title: '错误',
                    message: res.msg,
                    duration: '3000'
                  })
                }
              })
          } else {
            return false
          }
        } else {
          // 取消提交
        }
      })
    },
    getListData() {
      this.formData.contractAttachmentTypeItemList = [{ name: '' }]
      if (this.dialogType == '编辑附件') {
        console.log(this.listData)
        contractCorrelationApi.contractAttachmentTypeDetail(this.listData.id).then(res => {
          console.log(res.data)
          this.formData.name = res.data[0].name
          this.formData.classifyName = res.data[0].classifyName
          this.formData.classifyId = res.data[0].classifyId
          this.formData.typeId = res.data[0].typeId
          if (res.data[0].classifyName == '单项合同') {
            this.ContractType = this.singleContractType
          } else {
            this.ContractType = this.projectContractType
          }
          this.formData.typeArr = res.data[0].typeName.split(',')
          console.log('返回的复选框数据', this.formData.typeArr, this.ContractType)
          this.formData.typeName = res.data[0].typeName
          // this.formData.contractAttachmentTypeItemList = res.data[1].contractAttachmentTypeItemList
          this.formData.contractAttachmentTypeItemList = []
          for (let i = 0; i < res.data[1].contractAttachmentTypeItemList.length; i++) {
            this.formData.contractAttachmentTypeItemList.push({ name: res.data[1].contractAttachmentTypeItemList[i].name })
            // console.log(this.formData)
          }
          if (this.formData.contractAttachmentTypeItemList.length > 1) {
            this.delSpecialBtn = true
          }else{
            this.delSpecialBtn = false
          }
          console.log(this.formData)
        })
      } else {
        console.log('我也不知道干嘛')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.samples-mb-75 {
  margin-bottom: 7.5px !important;
}
.endInput:last-child {
  margin-bottom: 0px;
}
.spec-op {
  position: absolute;
  left: 290px;
  top: -2px;
}
.add-btn {
  width: 100%;
  border-style: dashed;
  background-color: #f2f2f2 !important;
}
</style>

<style lang="scss">

.add-star{
.el-form-item__label::before{
content: '*';
color: #e05e5e;
margin-right: 4px;
display: inline-block;
vertical-align: middle;
height: 32px;
line-height: 38px;
}
}
</style>
